package com.tianqu.tms.www.car.controller;

import java.text.SimpleDateFormat;
import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.WeChatMqApi;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn000205Bo;
import com.tianqu.tms.dto.MarketCarServiceDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.IntegralRegister;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.www.car.actionform.CarPendingLiftActionForm;
import com.tianqu.tms.www.car.viewhelper.CarPendingLiftViewHelper;


/**
 * @author mufeiyu
 * 库存取消 - 成功 controller
 */
public class CarStockCancleSuccessController extends TmsController{
	private Logger logger = Logger.getLogger(CarStockCancleSuccessController.class);
	public final static int FIXEDVALUE_3 = 3;
	public final static String LICENSEPLATE_NOEMPTY_STR = "【退费通知】车牌号码为{车牌号码}的{车辆名称}，因办理库存取消，系统自动退还预缴过户费{缴费金额}元，当前帐号余额为{帐号余额}元。";
	public final static String LICENSEPLATE_EMPTY_STR = "【退费通知】车架号（后6位）为{VIN码}的{车辆名称}，因办理库存取消，系统自动退还预缴过户费{缴费金额}元，当前帐号余额为${帐号余额}元";
	public final static String CAR_NAME = "车辆名称";
	public final static String CAR_NUMBER = "车牌号码";
	public final static String CAR_VIN = "VIN码";
	public final static String CAR_PAYMENT = "缴费金额";
	public final static String CAR_BALANCE = "帐号余额";
	public final static String SIGN = "\\$";
	public final static String BEFOREBRACE = "｛";
	public final static String LATERBRACE = "｝";
	
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			CarPendingLiftActionForm form = (CarPendingLiftActionForm)uc.getInputForm();
			CarPendingLiftViewHelper viewhelper = (CarPendingLiftViewHelper)uc.getAttribute(TmsConstants.VIEWHELP);
			
//			String path =ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY));
//			viewhelper.setAcceptorImage(path + form.getAcceptorImage());
			
			Car car = Car.getInstance();
			TmsUserProfile profile = uc.getUserProfile();
			
			//库存车辆信息表更新需要的数据
			car.setSerial(form.getSerial());
			car.setHandleType(FIXEDVALUE_3);
			
			//更新库存车辆信息表
			car.updateCarRegisterStatus(form.getSerial(), FIXEDVALUE_3);
			IntegralRegister register = new IntegralRegister();
			
			int price = 0;
			viewhelper.setIsAutoPayForRegister(Registry.getConfigFromDb(TmsConstants.ISAUTOPAYFORREGISTER));
			MarketCarServiceDto dto = car.findMarketCarService(form.getSerial());
			if(!"1".equals(viewhelper.getIsAutoPayForRegister())){
				price = dto.getTransferPrice();
				if(dto.getCheckPrice() == 1){
					// 1）更新 会员基本信息数据表（tms_member）
					// # 过户费余额（virtualMargin） = 过户费余额（virtualMargin） + 库存车辆业务表（tms_market_car_service）的流程表缴费（checkPrice）+ 交易票缴费（transferPrice）
					car.updateMember(viewhelper.getMemberId(), price);
					// c）插入 财务流水记录表（tms_integral_register）
					
					register.setMemberId(String.valueOf(viewhelper.getMemberId()));//会员编号
					register.setMemberType(1);//会员类型
					register.setChargeType(11);// # 业务处理类型（chargeType）为“11：过户费退费”
					register.setTransferPrice(price);// # 处理金额（transferPrice）为 库存车辆业务表（tms_market_car_service）的流程表缴费（checkPrice）+ 交易票缴费（transferPrice）
					register.setPlusMinus(1);// # 业务处理方式（plusMinus）为“1、增加”
					register.setRemark("库存登记预缴交易过户费退费");//# 备注（remarks）为“库存登记预缴交易过户费退费”
					register.setInsertUserId(profile.getUniqueId());//# 插入用户（insertUserId）为当前登录用户id
					register.setSerial(form.getSerial());
					//插入 财务流水记录表（tms_integral_register）
					register.insertRegisterInfo(register);
				}
			}
			
			// 3、更新 库存车辆业务表（tms_market_car_service）
			// # 车辆查验状态（checkStatus）为“1：未查验”
			// #  查验单图片（checkImgPath）、查验员（checkUser）、查验时间（checkTime）、查验有效时间（checkValidTime）为空
			// # 查验是否有效（isValid）为“3：无效”
			// # 流程表缴费（checkPrice）为“0”
			// # 交易票缴费（transferPrice）为“0”
			car.updateMarketCarService(form.getSerial());
			
			//库存车辆特殊处理记录表需要的数据
			car.setIsPush(form.getIsPush());
			car.setUpdateUserId(profile.getUniqueId());
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式 
			String updataTime = DateUtil.getCurrentTime();
			car.setUpdateTime(df.parse(updataTime));
			String pushContent = "";
			if(form.getIsPush() == 1)
			{
				Member member = Member.getInstance();
				member = member.findCarScoreByMemberId(viewhelper.getMemberId()+"");
				String virtualMargin = StringUtil.isNullOrBlank(member.getVirtualMargin())?"0":member.getVirtualMargin();
				if(viewhelper.getLicensePlate() == null || viewhelper.getLicensePlate().length() <= 0)
				{
					pushContent = getPushContent(viewhelper.getCarName(),getVin(viewhelper.getVin()),dto.getTransferPrice()+"",virtualMargin,2);
							
				} else {
					pushContent = getPushContent(viewhelper.getCarName(),viewhelper.getLicensePlate(),dto.getTransferPrice()+"",virtualMargin,1);
				}				
			}else if(form.getIsPush() == 2){			
				pushContent = "";
			}
			car.setPushContent(pushContent);
			
			car.setAcceptorImage(viewhelper.getAcceptorImage());
			
			//插入库存车辆特殊处理记录表
			car.insertCarHandleInfo(car);
			
			controller.commit();

			//接口编号：205；【TMS_web】库存取消 =>【TMS_app】同步 
			TransferDataSyn000205Bo transferDataSyn000205Bo = new TransferDataSyn000205Bo();
			Car carInfo = Car.getInstance();
			carInfo = car.findMemberId(form.getSerial());
			transferDataSyn000205Bo.setSerial(form.getSerial());
			transferDataSyn000205Bo.setMemberId(String.valueOf(carInfo.getMemberId()));
			transferDataSyn000205Bo.setRegisterStatus(carInfo.getRegisterStatus());
			transferDataSyn000205Bo.setPushFlag(car.getIsPush());
			transferDataSyn000205Bo.setPushText(car.getPushContent());
			transferDataSyn000205Bo.setMarketNo(TmsConstants.MARKET_NO);
			// # 库存取消业务并且进行退费处理情况，是否缴费为”1：是“、缴费金额和财务流水备注为业务插入到财务流水记录表（tms_integral_register）的处理金额（transferPrice）和备注（remarks）
			if(price > 0){
				// 是否缴费、缴费金额、财务流水备注[（transferPrice）和备注（remarks）]
				transferDataSyn000205Bo.setIdTollage(1);
				transferDataSyn000205Bo.setTransferPrice(register.getTransferPrice());
				transferDataSyn000205Bo.setRemarks(register.getRemark());
			}
			// # 库存取消业务并且没有进行退费处理情况，或者 库存信息过滤业务情况，是否缴费为”2：不是“、缴费金额和财务流水备注为空
			else {
				transferDataSyn000205Bo.setIdTollage(2);
				transferDataSyn000205Bo.setTransferPrice(0);
				transferDataSyn000205Bo.setRemarks("");
			}
			WeChatMqApi.getInstance().call(transferDataSyn000205Bo);

		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");		
	}
	public String getPushContent(String carName,String carInfo,String payment,String balance,int type)
			throws TmsDaoException {
		String contentStr = "";
		//车牌号不为空的库存取消信息
		if(type == 1)
		{
			contentStr = LICENSEPLATE_NOEMPTY_STR;
		} else if(type == 2){
			//车牌号为空的库存取消信息
			contentStr = LICENSEPLATE_EMPTY_STR;
		}
		contentStr = contentStr.replaceAll(SIGN, "").replaceAll(BEFOREBRACE, "").replaceAll(LATERBRACE, "");
	    contentStr = contentStr.replaceAll(CAR_NAME, carName).replaceAll(CAR_NUMBER, carInfo).replaceAll(CAR_VIN, carInfo).replaceAll(CAR_PAYMENT, payment).replaceAll(CAR_BALANCE, balance); 
		return contentStr;
	}
	
	private  String getVin(String vin){
		String r = vin;
		if(StringUtil.isNotBlank(vin) && vin.length() > 6){
			r = vin.substring(vin.length() - 6);
		}
		return r;
	}
}
